package com.csw.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class Demo05MapJoin {
    public static class MapJoinMapper extends Mapper<LongWritable,Text,Text,NullWritable>{
        //创建HashMap存储学生信息 id作为k,每行数据作为v
        HashMap<String,String>students=new HashMap<String,String>();
        //大表关联小表时,由于小表比较小,可以直接加载到内存
        // 在map执行之前执行
        // 每个map task都会执行一次
        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            //获取文件管理系统对象
            FileSystem fs = FileSystem.get(new Configuration());
            //打开小表文件
            FSDataInputStream open = fs.open(new Path("/data/students.txt"));
            //通过缓冲读取数据
            BufferedReader br = new BufferedReader(new InputStreamReader(open));
            String line;
            while ((line=br.readLine())!=null){
                String id=line.split(",")[0];
                students.put(id,line);
            }
        }

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String scores = line.substring(19);
            String id=line.split(",")[0];
            //以score中id获取student数据
            String stu = students.get(id);
            String s=stu+scores;
            context.write(new Text(s),NullWritable.get());
        }
    }
    public static void main(String[] args) throws Exception {
        Job job = Job.getInstance();
        job.setJobName("MapJoin");
        job.setJarByClass(Demo05MapJoin.class);
        //指定reduce task为0，即不允许reduce
        job.setNumReduceTasks(0);

        //指定map
        job.setMapperClass(MapJoinMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);
        //指定输入路径
        FileInputFormat.addInputPath(job,new Path("/data/score.txt"));

        //获取文件管理系统对象
        FileSystem fs = FileSystem.get(new Configuration());

        //指定输出路径(如果存在则删除)
        Path path = new Path("/data/out4");
        if (fs.exists(path)){
            fs.delete(path);
        }
        //指定输出路径
        FileOutputFormat.setOutputPath(job,path);
        //启动
        job.waitForCompletion(true);
    }
}
